<template>
  <view class="main-box">
    <!-- 筛选条件 -->
    <view class="filter-section">
      <view class="date-filter">
        <view
          class="date-item"
          @click="setDateFilter('today')"
          :class="{ active: dateFilter === 'today' }"
          >今日
        </view>
        <view
          class="date-item"
          @click="setDateFilter('week')"
          :class="{ active: dateFilter === 'week' }"
          >本周
        </view>
        <view
          class="date-item"
          @click="setDateFilter('month')"
          :class="{ active: dateFilter === 'month' }"
          >本月
        </view>
        <view
          class="date-item"
          @click="setDateFilter('all')"
          :class="{ active: dateFilter === 'all' }"
          >全部
        </view>
      </view>
      <view class="status-filter">
        <picker
          mode="selector"
          :range="statusOptions"
          range-key="label"
          @change="onStatusChange"
        >
          <view class="status-picker">
            <text>{{ currentStatus.label }}</text>
            <text class="picker-arrow">▼</text>
          </view>
        </picker>
      </view>
    </view>

    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input">
        <text class="search-icon iconfont icon-sousuo"></text>
        <input
          type="text"
          placeholder="搜索员工姓名或手机号"
          v-model="searchKeyword"
          @confirm="loadRecords(true)"
        />
      </view>
      <view class="search-btn" @click="loadRecords(true)">搜索</view>
    </view>

    <!-- 统计信息 -->
    <view class="statistics-section">
      <view class="stat-item">
        <view class="stat-num">{{ statistics.total || 0 }}</view>
        <view class="stat-label">总邀请</view>
      </view>
      <view class="stat-item">
        <view class="stat-num primary-color">{{ statistics.approved || 0 }}</view>
        <view class="stat-label">已通过</view>
      </view>
      <view class="stat-item">
        <view class="stat-num warning-color">{{ statistics.pending || 0 }}</view>
        <view class="stat-label">待审批</view>
      </view>
      <view class="stat-item">
        <view class="stat-num danger-color">{{ statistics.rejected || 0 }}</view>
        <view class="stat-label">已拒绝</view>
      </view>
    </view>

    <!-- 记录列表 -->
    <view class="records-list">
      <!-- 加载中状态 -->
      <view class="loading-container" v-if="isLoading">
        <view class="loading-spinner"></view>
        <view class="loading-text">加载中...</view>
      </view>

      <!-- 记录列表内容 -->
      <block v-else>
        <view class="record-item" v-for="(item, index) in records" :key="index">
          <view class="record-header">
            <view class="employee-info">
              <view class="employee-name">{{ item.employee_name }}</view>
              <view class="employee-mobile">{{ item.mobile }}</view>
            </view>
            <view class="record-status" :class="'status-' + item.status">
              {{ getStatusText(item.status) }}
            </view>
          </view>

          <view class="record-details">
            <view class="detail-item">
              <view class="detail-label">项目名称:</view>
              <view class="detail-value">{{ item.project_name }}</view>
            </view>
            <view class="detail-item">
              <view class="detail-label">所属企业:</view>
              <view class="detail-value">{{ item.enterprise_name }}</view>
            </view>
            <view class="detail-item">
              <view class="detail-label">开户状态:</view>
              <view class="detail-value">{{ item.account_status_name || "未开户" }}</view>
            </view>
            <view class="detail-item">
              <view class="detail-label">加入时间:</view>
              <view class="detail-value">{{ formatDateTime(item.created_time) }}</view>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view class="empty-container" v-if="records.length === 0">
          <image
            class="empty-image"
            src="/static/icons/empty.png"
            mode="aspectFit"
          ></image>
          <view class="empty-text">暂无邀请记录</view>
        </view>

        <!-- 加载更多 -->
        <view class="load-more" v-if="records.length > 0 && hasMore">
          <view class="load-more-text" @click="loadMore">加载更多</view>
        </view>

        <!-- 没有更多数据 -->
        <view class="no-more" v-if="records.length > 0 && !hasMore">
          <view class="no-more-text">已加载全部数据</view>
        </view>
      </block>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      projectId: 0, // 项目ID
      enterpriseId: 0, // 企业ID

      // 数据加载状态
      isLoading: false,

      // 筛选条件
      dateFilter: "all", // 日期筛选: today, week, month, all
      statusOptions: [
        {
          value: -1,
          label: "全部状态",
        },
        {
          value: 0,
          label: "待审批",
        },
        {
          value: 1,
          label: "审批中",
        },
        {
          value: 2,
          label: "已通过",
        },
        {
          value: 3,
          label: "已拒绝",
        },
      ],
      currentStatus: {
        value: -1,
        label: "全部状态",
      },
      searchKeyword: "", // 搜索关键词

      // 分页信息
      page: 1,
      pageSize: 10,
      hasMore: true,

      // 数据
      statistics: {
        total: 0,
        approved: 0,
        pending: 0,
        rejected: 0,
      },
      records: [],
    };
  },
  onLoad(options) {
    // 检查登录状态
    if (!this.checkLogin()) {
      return;
    }

    // 获取项目ID和企业ID
    if (options.project_id) {
      this.projectId = parseInt(options.project_id);
    }

    if (options.enterprise_id) {
      this.enterpriseId = parseInt(options.enterprise_id);
    }

    // 加载数据
    this.loadStatistics();
    this.loadRecords(true);
  },
  onPullDownRefresh() {
    // 下拉刷新
    this.loadStatistics();
    this.loadRecords(true, () => {
      uni.stopPullDownRefresh();
    });
  },
  onReachBottom() {
    // 上拉加载更多
    if (this.hasMore && !this.isLoading) {
      this.loadMore();
    }
  },
  methods: {
    // 检查登录状态
    checkLogin() {
      const token = uni.getStorageSync("token");
      if (!token) {
        uni.redirectTo({
          url: "/pages/login",
        });
        return false;
      }
      return true;
    },

    // 返回上一页
    goBack() {
      uni.navigateBack();
    },

    // 设置日期筛选
    setDateFilter(filter) {
      if (this.dateFilter === filter) return;

      this.dateFilter = filter;
      this.loadRecords(true);
    },

    // 状态筛选变更
    onStatusChange(e) {
      const index = e.detail.value;
      this.currentStatus = this.statusOptions[index];
      this.loadRecords(true);
    },

    // 加载统计数据
    loadStatistics() {
      // 构建请求参数
      const params = {};

      // 添加项目ID或企业ID（如果有）
      if (this.projectId) {
        params.project_id = this.projectId;
      }

      if (this.enterpriseId) {
        params.enterprise_id = this.enterpriseId;
      }

      // 添加日期筛选
      if (this.dateFilter !== "all") {
        const { start_date, end_date } = this.getDateRange(this.dateFilter);
        params.start_date = start_date;
        params.end_date = end_date;
      }

      // 发送请求
      this.$request.inviteStatistics(params, (res) => {
        // 更新统计数据
        const summary = res.summary || {};
        this.statistics = {
          total: summary.total || 0,
          approved: summary.status?.approved || 0,
          pending: (summary.status?.pending || 0) + (summary.status?.reviewing || 0),
          rejected: summary.status?.rejected || 0,
        };
      });
    },

    // 加载记录列表
    loadRecords(reset = false, callback) {
      // 如果是重置，则重置页码
      if (reset) {
        this.page = 1;
        this.hasMore = true;
      }

      // 如果没有更多数据且不是重置操作，则直接返回
      if (!this.hasMore && !reset) {
        if (typeof callback === "function") {
          callback();
        }
        return;
      }

      // 设置加载状态
      this.isLoading = true;

      // 构建请求参数
      const params = {
        page: this.page,
        pageSize: this.pageSize,
      };

      // 添加项目ID或企业ID（如果有）
      if (this.projectId) {
        params.project_id = this.projectId;
      }

      if (this.enterpriseId) {
        params.enterprise_id = this.enterpriseId;
      }

      // 添加状态筛选
      if (this.currentStatus.value !== -1) {
        params.status = this.currentStatus.value;
      }

      // 添加日期筛选
      if (this.dateFilter !== "all") {
        const { start_date, end_date } = this.getDateRange(this.dateFilter);
        params.start_date = start_date;
        params.end_date = end_date;
      }

      // 添加搜索关键词
      if (this.searchKeyword) {
        params.keyword = this.searchKeyword;
      }

      // 发送请求
      this.$request.inviteRecords(
        params,
        (res) => {
          const list = res.list || [];
          const total = res.total || 0;

          // 如果是重置，则清空记录列表
          if (reset) {
            this.records = list;
          } else {
            // 否则追加数据
            this.records = [...this.records, ...list];
          }

          // 更新是否有更多数据
          this.hasMore = this.records.length < total;

          // 更新页码
          if (list.length > 0) {
            this.page++;
          }
        },
        (err) => {
          // 请求失败处理
          if (reset) {
            this.records = [];
          }
          this.hasMore = false;
        },
        () => {
          // 设置加载状态
          this.isLoading = false;
          // 执行回调
          if (typeof callback === "function") {
            callback();
          }
        }
      );
    },

    // 加载更多数据
    loadMore() {
      if (this.isLoading || !this.hasMore) return;

      this.loadRecords(false);
    },

    // 获取日期范围
    getDateRange(filter) {
      const now = new Date();
      const start = new Date();
      const end = new Date();

      switch (filter) {
        case "today":
          // 今日: 当天开始到当天结束
          start.setHours(0, 0, 0, 0);
          end.setHours(23, 59, 59, 999);
          break;
        case "week":
          // 本周: 本周一到当天
          const day = now.getDay() || 7; // 如果是周日，getDay()返回0，转换为7
          start.setDate(now.getDate() - day + 1); // 设置为本周一
          start.setHours(0, 0, 0, 0);
          end.setHours(23, 59, 59, 999);
          break;
        case "month":
          // 本月: 本月1号到当天
          start.setDate(1); // 设置为本月1号
          start.setHours(0, 0, 0, 0);
          end.setHours(23, 59, 59, 999);
          break;
        default:
          // 全部: 不设限制
          return {};
      }

      return {
        start_date: this.formatDate(start),
        end_date: this.formatDate(end),
      };
    },

    // 格式化日期为YYYY-MM-DD
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");

      return `${year}-${month}-${day}`;
    },

    // 格式化日期时间
    formatDateTime(dateStr) {
      if (!dateStr) return "未知";

      try {
        const date = new Date(dateStr);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");

        return `${year}-${month}-${day} ${hours}:${minutes}`;
      } catch (e) {
        return dateStr;
      }
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: "待审批",
        1: "审批中",
        2: "已通过",
        3: "已拒绝",
      };
      return statusMap[status] || "未知状态";
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/static/scss/variables.scss";

.navbar-left {
  width: 80rpx;
  display: flex;
  align-items: center;
}

.back-icon {
  font-size: 36rpx;
  color: #333;
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.navbar-right {
  width: 80rpx;
}

/* 筛选条件部分 */
.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #f0f0f0;
}

.date-filter {
  display: flex;
}

.date-item {
  padding: 8rpx 20rpx;
  font-size: 26rpx;
  color: #666;
  margin-right: 10rpx;
  border-radius: 30rpx;
}

.date-item.active {
  background-color: $colorPrimaryLight3;
  color: $colorPrimary;
}

.status-picker {
  display: flex;
  align-items: center;
  font-size: 26rpx;
  color: #333;
}

.picker-arrow {
  font-size: 20rpx;
  color: #999;
  margin-left: 10rpx;
}

/* 搜索栏 */
.search-bar {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
}

.search-input {
  flex: 1;
  display: flex;
  align-items: center;
  height: 70rpx;
  background-color: #f5f5f5;
  border-radius: 35rpx;
  padding: 0 20rpx;
}

.search-icon {
  margin-right: 10rpx;
  padding-bottom: -1px;
  color: #aaa;
}

.search-input input {
  flex: 1;
  height: 70rpx;
  font-size: 26rpx;
  color: #333;
}

.search-btn {
  width: 120rpx;
  height: 70rpx;
  line-height: 70rpx;
  text-align: center;
  background-color: $colorPrimary;
  color: #fff;
  font-size: 26rpx;
  border-radius: 35rpx;
  margin-left: 20rpx;
}

/* 统计信息部分 */
.statistics-section {
  display: flex;
  justify-content: space-between;
  padding: 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.stat-item {
  text-align: center;
}

.stat-num {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #999;
}

/* 统计信息部分 */
.statistics-section {
  display: flex;
  justify-content: space-between;
  padding: 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.stat-item {
  text-align: center;
}

.stat-num {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #999;
}

.primary-color {
  color: $colorPrimary;
}

.warning-color {
  color: #ff9500;
}

.danger-color {
  color: #ff3b30;
}

/* 记录列表部分 */
.records-list {
  flex: 1;
  padding: 0 30rpx 30rpx;
}

/* 加载中状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx 0;
}

.loading-spinner {
  width: 40rpx;
  height: 40rpx;
  border: 3rpx solid rgba(64, 128, 255, 0.3);
  border-radius: 50%;
  border-top-color: $colorPrimary;
  animation: spin 0.8s linear infinite;
  margin-bottom: 20rpx;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.loading-text {
  font-size: 26rpx;
  color: #999;
}

/* 记录项 */
.record-item {
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.employee-info {
  flex: 1;
}

.employee-name {
  font-size: 30rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 6rpx;
}

.employee-mobile {
  font-size: 26rpx;
  color: #999;
}

.record-status {
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}

.status-0 {
  background-color: #fff9f0;
  color: #ff9500;
}

.status-1 {
  background-color: #e6f0ff;
  color: $colorPrimary;
}

.status-2 {
  background-color: #f0fff5;
  color: #19be6b;
}

.status-3 {
  background-color: #fff5f5;
  color: #ff3b30;
}

.record-details {
  padding: 20rpx 30rpx;
}

.detail-item {
  display: flex;
  margin-bottom: 10rpx;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-label {
  width: 160rpx;
  font-size: 26rpx;
  color: #999;
}

.detail-value {
  flex: 1;
  font-size: 26rpx;
  color: #333;
}

/* 空状态 */
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

/* 加载更多 */
.load-more {
  text-align: center;
  padding: 30rpx 0;
}

.load-more-text {
  font-size: 26rpx;
  color: $colorPrimary;
  display: inline-block;
  padding: 10rpx 30rpx;
}

/* 没有更多数据 */
.no-more {
  text-align: center;
  padding: 30rpx 0;
}

.no-more-text {
  font-size: 26rpx;
  color: #999;
}
</style>
